package com.bsj.sipgateway.sip;

import com.bsj.power.common.def.entity.gb28181.Device;
import com.bsj.power.common.def.enums.CmdLogEnum;
import com.bsj.power.common.mapper.CmdLogMapper;
import com.bsj.sipgateway.cache.DeviceCache;
import com.bsj.sipgateway.command.RocketMqCommand;
import com.bsj.sipgateway.common.constant.Constants;
import com.bsj.sipgateway.config.SipConfig;
import com.bsj.sipgateway.mq.producer.CommandUpProducer;
import com.bsj.sipgateway.sip.bean.Command;
import com.bsj.power.common.def.entity.log.CmdLog;
import com.bsj.sipgateway.sip.bean.VideoStreamSession;
import com.bsj.sipgateway.sip.event.SipSubscribe;
import com.bsj.sipgateway.sip.session.CallIdManager;
import com.bsj.sipgateway.sip.session.CommandManager;
import com.bsj.sipgateway.sip.session.VideoStreamSessionManager;
import com.bsj.sipgateway.sip.transmit.SIPProcessorFactory;
import com.bsj.sipgateway.sip.transmit.response.ISIPResponseProcessor;
import com.bsj.sipgateway.util.CommandDownType;
import gov.nist.javax.sip.SipStackImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.sip.*;
import javax.sip.header.CallIdHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Response;
import java.text.ParseException;
import java.util.Date;
import java.util.Properties;
import java.util.TooManyListenersException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SipLayer implements SipListener {

    @Autowired
    private SipConfig sipConfig;

    @Autowired
    private SIPProcessorFactory processorFactory;

    @Autowired
    private SipSubscribe sipSubscribe;

    private SipStack sipStack;

    private SipFactory sipFactory;

    @Autowired
    private CommandUpProducer commandUpProducer;

    /**
     * 消息处理器线程池
     */
    private ThreadPoolExecutor processThreadPool;

    @Autowired
    private VideoStreamSessionManager streamSession;

    @Autowired
    private CmdLogMapper cmdLogMapper;

    @Bean("initSipServer")
    public ThreadPoolExecutor initSipServer() {

        int processThreadNum = Runtime.getRuntime().availableProcessors() * 10;
        LinkedBlockingQueue<Runnable> processQueue = new LinkedBlockingQueue<Runnable>(10000);
        processThreadPool = new ThreadPoolExecutor(processThreadNum, processThreadNum,
                0L, TimeUnit.MILLISECONDS, processQueue,
                new ThreadPoolExecutor.CallerRunsPolicy());
        return processThreadPool;
    }

    @Bean("sipFactory")
    @DependsOn("initSipServer")
    public SipFactory createSipFactory() {
        sipFactory = SipFactory.getInstance();
        sipFactory.setPathName("gov.nist");
        return sipFactory;
    }

    @Bean("sipStack")
    @DependsOn({"initSipServer", "sipFactory"})
    public SipStack createSipStack() throws PeerUnavailableException {
        Properties properties = new Properties();
        properties.setProperty("javax.sip.STACK_NAME", "GB28181_SIP");
        properties.setProperty("javax.sip.IP_ADDRESS", sipConfig.getSipIp());
        properties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "false");

        properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "0");
        properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "sip_server_log");
        properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "sip_debug_log");
        sipStack = (SipStackImpl) sipFactory.createSipStack(properties);
        return sipStack;
    }

    @Bean("tcpSipProvider")
    @DependsOn("sipStack")
    public SipProvider startTcpListener() {
        ListeningPoint tcpListeningPoint = null;
        SipProvider tcpSipProvider = null;
        try {
            tcpListeningPoint = sipStack.createListeningPoint(sipConfig.getSipIp(), sipConfig.getSipPort(), "TCP");
            tcpSipProvider = sipStack.createSipProvider(tcpListeningPoint);
            tcpSipProvider.addSipListener(this);
            log.info("Sip Server TCP 启动成功 port {" + sipConfig.getSipPort() + "}");
        } catch (TransportNotSupportedException | InvalidArgumentException | TooManyListenersException | ObjectInUseException e) {
            log.error(String.format("创建SIP服务失败: %s", e.getMessage()));
        }
        return tcpSipProvider;
    }

    @Bean("udpSipProvider")
    @DependsOn("sipStack")
    public SipProvider startUdpListener() throws Exception {
        ListeningPoint udpListeningPoint = sipStack.createListeningPoint(sipConfig.getSipIp(), sipConfig.getSipPort(), "UDP");
        SipProvider udpSipProvider = sipStack.createSipProvider(udpListeningPoint);
        udpSipProvider.addSipListener(this);
        log.info("Sip Server UDP 启动成功 port {" + sipConfig.getSipPort() + "}");
        return udpSipProvider;
    }

    /**
     * SIP服务端接收消息的方法 Content 里面是GBK编码 This method is called by the SIP stack when a
     * new request arrives.
     */
    @Override
    public void processRequest(RequestEvent evt) {
        log.debug(evt.getRequest().toString());
        // 由于jainsip是单线程程序，为提高性能并发处理
        processThreadPool.execute(() -> {
            if (processorFactory != null) {
                processorFactory.createRequestProcessor(evt).process();
            }
        });
    }

    @Override
    public void processResponse(ResponseEvent evt) {
        Response response = evt.getResponse();
//        log.debug(evt.getResponse().toString());
        int status = response.getStatusCode();
        if ((status >= 200) && (status < 300)) { // Success!
            ISIPResponseProcessor processor = processorFactory.createResponseProcessor(evt);
            try {
                processor.process(evt, this, sipConfig);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (evt.getResponse() != null && sipSubscribe.getOkSubscribesSize() > 0) {
                CallIdHeader callIdHeader = (CallIdHeader) evt.getResponse().getHeader(CallIdHeader.NAME);
                if (callIdHeader != null) {
                    SipSubscribe.Event subscribe = sipSubscribe.getOkSubscribe(callIdHeader.getCallId());
                    if (subscribe != null) {
                        subscribe.response(evt);
                    }
                }
            }
        } else if ((status >= 100) && (status < 200)) {
            // 增加其它无需回复的响应，如101、180等
//            log.info("接收到100-200的response响应！status：" + status + ",message:" + response.getReasonPhrase());
        } else {
//            log.error("接收到失败的response响应！status：" + status + ",message:" + response.getReasonPhrase()/* .getContent().toString()*/);
            CallIdHeader callIdHeader = null;
            if (evt.getResponse() != null) {
                callIdHeader = (CallIdHeader) evt.getResponse().getHeader(CallIdHeader.NAME);
            }
            if (callIdHeader != null) {
                if (sipSubscribe.getErrorSubscribesSize() > 0) {
                    SipSubscribe.Event subscribe = sipSubscribe.getErrorSubscribe(callIdHeader.getCallId());
                    if (subscribe != null) {
                        subscribe.response(evt);
                    }
                }
                //响应mq
                int statusCode = evt.getResponse().getStatusCode();
                //找到对应的uuid
                String deviceId = CallIdManager.getDeviceId(callIdHeader.getCallId());
                ViaHeader viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
                Device device = DeviceCache.getDevice(deviceId);
                Long did = device.getId();
                Command cache = CommandManager.get(deviceId, viaHeader.getBranch());
                if (statusCode == Response.SERVICE_UNAVAILABLE) {//返回失败，服务不可达
                    log.warn("设备响应invite失败：code：" + statusCode + ",msg:" + response.getReasonPhrase());
//                    ackError(deviceId, cache, "服务不可达");
                } else {
                    log.warn("设备响应invite失败：code：" + statusCode + ",msg:" + response.getReasonPhrase());
//                    ackError(deviceId, cache, response.getReasonPhrase());
                }

//                for (int i = 1; i <= 4; i++) {
//                    streamSession.remove(deviceId, Constants.PLAYER_PREFIX, "" + i);
//                    streamSession.remove(deviceId, Constants.PLAY_BLACK_PREFIX, "" + i);
//                    streamSession.remove(deviceId, Constants.BROADCAST_PREFIX, "" + i);
//                }

            }
        }
        CallIdHeader callIdHeader = null;
        ViaHeader viaHeader = null;
        if (evt.getResponse() != null) {
            callIdHeader = (CallIdHeader) evt.getResponse().getHeader(CallIdHeader.NAME);
            viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
        }
        String deviceId = null;
        if (callIdHeader != null) {
            deviceId = CallIdManager.getDeviceId(callIdHeader.getCallId());
        }
        Device device = null;
        if (deviceId != null) {
            device = DeviceCache.getDevice(deviceId);
        }
        Command cache = null;
        if (viaHeader != null) {
            cache = CommandManager.get(deviceId, viaHeader.getBranch());
        }

        // 记录指令收发日志
        if (device != null && cache != null) {
            int cmdType = cache.getCmdType();
            String sessionType = cache.getSessionType();

            CmdLog cmdLog = new CmdLog();
            cmdLog.setDeviceId(device.getDeviceId());
            cmdLog.setDeviceName(device.getNickName());
            if (cmdType == CommandDownType.REAL_VIDEO_OPEN_CMD) {
                cmdLog.setType(CmdLogEnum.TYPE_PLAY.getDesc());
            } else if (cmdType == CommandDownType.DEV_VOD_MEDIA_TRANS) {
                cmdLog.setType(CmdLogEnum.TYPE_PLAY_BACK.getDesc());
            }
            cmdLog.setState(CmdLogEnum.STATE_RECEIVE.getDesc());
            cmdLog.setContent("设备响应status=" + status + ",message:" + response.getReasonPhrase());
            cmdLog.setTime(new Date());
            cmdLogMapper.insert(cmdLog);
        }


    }

    /**
     * <p>
     * Title: processTimeout
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @param timeoutEvent
     */
    @Override
    public void processTimeout(TimeoutEvent timeoutEvent) {
        // TODO Auto-generated method stub

    }

    /**
     * <p>
     * Title: processIOException
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @param exceptionEvent
     */
    @Override
    public void processIOException(IOExceptionEvent exceptionEvent) {
        // TODO Auto-generated method stub

    }

    /**
     * <p>
     * Title: processTransactionTerminated
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @param transactionTerminatedEvent
     */
    @Override
    public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {
        // TODO Auto-generated method stub

    }

    /**
     * <p>
     * Title: processDialogTerminated
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @param dialogTerminatedEvent
     */
    @Override
    public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
        // TODO Auto-generated method stub

    }

    private void ackError(String deviceId, Command cache, String errMsg) {
        RocketMqCommand command = new RocketMqCommand(cache.getCmdType(), cache.getUuid(), deviceId, 0);
        command.setRetMsg(errMsg);
        String sqlType = "";
        switch (cache.getCmdType()) {
            case CommandDownType.REAL_MEDIA_OPEN_CMD:
            case CommandDownType.REAL_VIDEO_OPEN_CMD:
                sqlType = Constants.PLAYER_PREFIX;
                break;

            //打开历史视频
            case CommandDownType.DEV_VOD_MEDIA_TRANS:
                sqlType = Constants.PLAY_BLACK_PREFIX;
                break;
            //打开对讲
            case CommandDownType.REAL_INTERCOM_OPEN_CMD:
                sqlType = Constants.BROADCAST_PREFIX;
                break;
        }
//        commandUpProducer.send(command, sqlType);
    }

}
